package com.yan_jiu_sheng.LeetCodeHot100.AC;

/**
 * https://leetcode.cn/problems/number-of-islands/?envType=study-plan-v2&envId=top-100-liked
 * 通过
 *
 * @author yulongTian
 * @create 2024-06-27 13:16
 */
public class Test51 {
    public static void main(String[] args) {

    }

    public int numIslands(char[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int ans = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    ans++;
                    dfs(grid, i, j);
                }
            }
        }
        return ans;
    }

    private void dfs(char[][] grid, int cur_i, int cur_j) {
        if (grid[cur_i][cur_j] == '0') {
            return;
        }
        grid[cur_i][cur_j] = '0';
        // 上
        if (cur_i - 1 >= 0) {
            dfs(grid, cur_i - 1, cur_j);
        }
        // 下
        if (cur_i + 1 < grid.length) {
            dfs(grid, cur_i + 1, cur_j);
        }
        // 左
        if (cur_j - 1 >= 0) {
            dfs(grid, cur_i, cur_j - 1);
        }
        // 右
        if (cur_j + 1 < grid[0].length) {
            dfs(grid, cur_i, cur_j + 1);
        }
    }


}
